package com.wsx.ones.boot.core.redis;

import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;

public class RedisConfig {

	public static Map<String, List<RedisBean>> redisGroup = null;
	
	private static ReentrantLock lock = new ReentrantLock();
	
	
	private RedisConfig() {
	}
	
	public static Map<String, List<RedisBean>> getRedisGroup() {
		lock.lock();
		if (null == redisGroup) {
			Document document = readRedisXML();
			redisGroup = getRedisGroupByDocument(document);
		}
		lock.unlock();
		return redisGroup;
	}

	@SuppressWarnings("unchecked")
	private static Map<String, List<RedisBean>> getRedisGroupByDocument(Document document) {
		Map<String, List<RedisBean>> redisMap = new HashMap<String, List<RedisBean>>();
		try {
			Element root = document.getRootElement();
			List<Element> nodes = root.elements("clusterGroup");
			int size = nodes.size();
			for (int i = 0; i < size; i++) {
				Element items = nodes.get(i);
				String groupName = items.attributeValue("name");
				String selectDB = items.attributeValue("selectdb");
				
				List<Element> servers = items.elements();
				List<RedisBean> redisBeans = getRedisList(servers,selectDB);
				redisMap.put(groupName, redisBeans);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return redisMap;
	}

	private static List<RedisBean> getRedisList(List<Element> servers, String selectDB) {
		int size = servers.size();
		List<RedisBean> redisBeans = new ArrayList<RedisBean>(size);
		RedisBean redisBean = null;
		for (int i = 0; i < size; i++) {
			Element element = servers.get(i);
			String host = element.attributeValue("host");
			String port = element.attributeValue("port");
			
			String timeout = element.attributeValue("timeout");
			String weight = element.attributeValue("weight");
			String name = element.attributeValue("name");
			
			//redisBean = new RedisBean(host, port, selectDB);
			redisBean = new RedisBean(host, port, selectDB, timeout, weight, name);
			redisBeans.add(redisBean);
		}
		return redisBeans;
	}

	private static Document readRedisXML() {
		SAXReader reader = new SAXReader();
		
		Document document = null;
		Reader xmlReader = null;
		try {
			Resource resource = new ClassPathResource("/config/redis/redisConfig.xml");
			EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
			xmlReader = encodedResource.getReader();
			document = reader.read(xmlReader);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != xmlReader) {
				try {
					xmlReader.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
		return document;
	}
}
